package nobu.nakata.nfcfare.resource.impl;

import javax.jdo.PersistenceManager;

import net.sf.jsr107cache.Cache;
import nobu.nakata.nfcfare.resource.ITrainResource;
import nobu.nakata.nfcfare.resource.item.ITrainResourceItem;
import nobu.nakata.nfcfare.resource.mapper.TrainResourceMapper;
import nobu.nakata.nfcfare.resource.util.ServiceResourceUtil;

import org.restlet.data.Status;
import org.restlet.resource.ResourceException;
import org.restlet.resource.ServerResource;

import com.google.appengine.api.users.User;

public class TrainResource extends ServerResource implements ITrainResource {
	static private final String KEY_TRAIN_CODE	= "trainCode";
	
	
	/* (non-Javadoc)
	 * @see nobu.nakata.nfcfare.resource.ITrainResource#retrieve()
	 */
	@Override
	public ITrainResourceItem retrieve() {
		PersistenceManager pm = null;
		try {
			Cache cache = ServiceResourceUtil.makeCache();
			pm = ServiceResourceUtil.makeStorage();			
			User viewer = ServiceResourceUtil.getViewer();
			long trainCodeNum = getTrainCode();
			if (trainCodeNum <= 0)
				throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST);
			TrainResourceMapper resourceMapper = new TrainResourceMapper(cache, pm, viewer);
			ITrainResourceItem result = resourceMapper.findByTrainStationCode(trainCodeNum);
			if (result == null)
				throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND);
			return result;
		} catch(ResourceException e) {
			throw e;
		} catch(Throwable th) {
			throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST);
		} finally {
			if (pm != null)
				pm.close();
		}
	}

	
	/* (non-Javadoc)
	 * @see nobu.nakata.nfcfare.resource.ITrainResource#update(nobu.nakata.nfcfare.resource.item.TrainResourceItem)
	 */
	@Override
	public ITrainResourceItem update(ITrainResourceItem updateResourceItem) {
		PersistenceManager pm = null;
		try {
			User viewer = ServiceResourceUtil.getViewer();
			if (viewer == null)
				throw new ResourceException(Status.CLIENT_ERROR_FORBIDDEN);
			long trainCodeNum = getTrainCode();
			if (trainCodeNum <= 0 || updateResourceItem.getTrainCode() != trainCodeNum)
				throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST);
			Cache cache = ServiceResourceUtil.makeCache();
			pm = ServiceResourceUtil.makeStorage();
			TrainResourceMapper resourceMapper = new TrainResourceMapper(cache, pm, viewer);
			resourceMapper.set(updateResourceItem);
			return updateResourceItem;
		} catch(ResourceException e) {
			throw e;
		} catch(Throwable th) {
			throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST);
		} finally {
			if (pm != null)
				pm.close();
		}
	}
	
	
	private long getTrainCode() {
		try {
			return Long.parseLong((String) getRequest().getAttributes().get(KEY_TRAIN_CODE));
		} catch(Throwable th) {
			return 0;
		}
	}

}
